package com.eboss2.sbs.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.base.BaseActivity;
import com.eboss2.sbs.adapter.ExpressListAdapter;
import com.eboss2.sbs.config.Config;
import com.eboss2.sbs.http.HttpUtil;
import com.eboss2.sbs.model.ExpressInfo;
import com.eboss2.sbs.model.MessageEvent;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.mytools.tool.activityManager.MyActivityManager;
import com.tool.utils.utils.StringUtils;
import com.tool.utils.utils.ToastUtils;
import com.tool.utils.view.MyListView;
import com.tool.utils.view.ShapeView;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ActivityGetEms extends BaseActivity {


    @BindView(R.id.titleback_btn_back)
    LinearLayout titlebackBtnBack;
    @BindView(R.id.et_ems_name)
    EditText etEmsName;
    @BindView(R.id.et_ems_no)
    EditText etEmsNo;
    @BindView(R.id.iv_scan)
    ImageView ivScan;
    @BindView(R.id.listview)
    MyListView listview;
    @BindView(R.id.tv_save)
    ShapeView tvSave;


    private ExpressInfo vo;
    private List<ExpressInfo> expressInfos = new ArrayList<>();
    private ExpressListAdapter adapter;

    private long orderId;
    private String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_ems_no);
        ButterKnife.bind(this);
        MyActivityManager.getInstance().addActivity(this);
        initView();
    }

    private void initView() {
        RelativeLayout relativeLayout = relativeLayout(R.id.lv_heard);
        relativeLayout.setBackgroundColor(getResources().getColor(R.color.statusBar));
        showView(R.id.titleback_btn_back, true);
        setTvText(R.id.tv_title, "发货");

        orderId = getIntent().getLongExtra("id", 0);
        if (orderId == 0) {
            finish();
            return;
        }

        type = getIntent().getStringExtra("type");


        adapter = new ExpressListAdapter(mContext, expressInfos);
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {


                vo = expressInfos.get(i);
                etEmsName.setText(vo.getExpress_name());
                etEmsName.setSelection(etEmsName.getText().toString().length());
            }
        });


        etEmsName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (delayRun != null) {
                    //每次editText有变化的时候，则移除上次发出的延迟线程
                    handler.removeCallbacks(delayRun);
                }

                //延迟800ms，如果不再输入字符，则执行该线程的run方法
                handler.postDelayed(delayRun, 500);
            }
        });


    }


    private Handler handler = new Handler();

    /**
     * 延迟线程，看是否还有下一个字符输入
     */
    private Runnable delayRun = new Runnable() {

        @Override
        public void run() {
            loadEmsShortName();
        }
    };

    private void loadEmsShortName() {

        if (StringUtils.isBlank(etEmsName.getText().toString().trim())) {
            return;
        }

//        showProgress("加载中...");
        String url = Config.SBS_GET_EMS_SHORT_NAME;
        RequestParams params = new RequestParams();
        params.put("expressName", etEmsName.getText().toString().trim());

        HttpUtil.get(url, params, new HttpUtil.RequestListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void success(String response) {
                disShowProgress();
                try {

                    if (!StringUtils.isBlank(response)) {
                        JSONObject result = new JSONObject(response);
                        List<ExpressInfo> datas = new Gson().fromJson(result.optString("result"), new TypeToken<List<ExpressInfo>>() {
                        }.getType());
                        if (datas != null && datas.size() > 0) {
                            expressInfos.clear();
                            expressInfos.addAll(datas);
                            adapter.notifyDataSetChanged();
                        } else {
                            ToastUtils.showShort(mContext, "暂不支持该快递公司");
                        }
                    }


                } catch (Exception e) {
                    e.getMessage();

                }
            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 1:
                // 处理扫描结果（在界面上显示）
                String str = data.getStringExtra(CodeUtils.RESULT_STRING);
                etEmsNo.setText(str);
                break;

            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


    @OnClick({R.id.titleback_btn_back, R.id.iv_scan, R.id.tv_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleback_btn_back:
                finish();
                break;
            case R.id.iv_scan:
                startActivityForResult(new Intent(mContext, CaptureActivity.class), 1);
                break;

            case R.id.tv_save:
                doCommit();
                break;
        }
    }

    private void doCommit() {

        if (vo == null) {
            ToastUtils.showShort(mContext, "请选择快递公司");
            return;
        }
        if (StringUtils.isBlank(etEmsNo.getText().toString().trim())) {
            ToastUtils.showShort(mContext, "请输入或扫描单号");
            return;
        }


        showProgress("加载中...");
        String url = Config.SBS_SEND_FH;
        RequestParams params = new RequestParams();
        params.put("id", orderId);
        params.put("expressName", vo.getExpress_name());
        params.put("expressNo", etEmsNo.getText().toString().trim());
        params.put("expressShort", vo.getExpress_short());
        params.put("status", 6);

        HttpUtil.get(url, params, new HttpUtil.RequestListener() {

            @SuppressWarnings("unchecked")
            @Override
            public void success(String response) {
                disShowProgress();
                try {

                    JSONObject result = new JSONObject(response);
                    if (!result.optBoolean("status")) {
                        showErrorMsg(result.getString("message"));
                        return;
                    }

                    showErrorMsg(result.getString("message"));
                    if (!StringUtils.isBlank(type)) {
                        EventBus.getDefault().post(new MessageEvent(type));
                    }
                    finish();


                } catch (Exception e) {
                    e.getMessage();

                }
            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }
        });
    }
}
